package xyz.labmem.base.sys.module.auth.service.impl

import cn.dev33.satoken.stp.StpUtil
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service
import xyz.labmem.base.core.consts.*
import xyz.labmem.base.core.result.RU
import xyz.labmem.base.core.result.RV
import xyz.labmem.base.sys.context.AuthRedisService
import xyz.labmem.base.sys.module.auth.controller.request.AuthRequest
import xyz.labmem.base.sys.module.auth.entity.LoginEntity
import xyz.labmem.base.sys.module.auth.service.AuthService
import xyz.labmem.base.sys.module.config.service.SysConfigService
import xyz.labmem.base.sys.module.user.entity.SysUser
import xyz.labmem.base.sys.module.user.mapper.SysUserMapper
import xyz.labmem.base.sys.util.LogManager

/**
 * @Author lty
 * @Date 2021/12/20 14:04
 */
@Service
class AuthServiceImpl(
    private var authRedisService: AuthRedisService,
    private var sysUserMapper: SysUserMapper,
    private var passwordEncoder: PasswordEncoder,
    private var sysConfigService: SysConfigService
) : AuthService {

    override fun login(req: AuthRequest, isAdmin: Int): RV<*> {
        //通过账号获取用户
        val user = SysUser().selectOne(
            KtQueryWrapper(SysUser::class.java)
                .eq(SysUser::account, req.account)
                .eq(isAdmin == 1, SysUser::admin, isAdmin)
        )
        return if (user != null) {
            if (passwordEncoder.matches(req.password, user.password)) {
                var sysConfig = sysConfigService.getConfigByCode(TIME_CONFIG_ID)
                if(sysConfig!=null){
                    StpUtil.stpLogic.config.activityTimeout = sysConfig.activityTimeout!!
                    StpUtil.stpLogic.config.timeout = sysConfig.timeout!!
                }

                //登录
                StpUtil.login(user.id)
                //session注入当前登录用户信息
                StpUtil.getSession().set(USER_SESSION_KEY, user)
                //权限获取
                updateUserPermission(user.id!!)
                updateUserRole(user.id!!)
                var sysUserOnline =LogManager.me().executeLoginLog(user, true, null)
                //用户信息存入redis
                StpUtil.getSession().set(userKeyPrefix+StpUtil.getTokenValue(), sysUserOnline)
            //    authRedisService.setUserEntity(sysUserOnline)
                LogManager.me().log()
                RU.success(LoginEntity().apply { tokenInfo= StpUtil.getTokenInfo();userInfo=user;})

            } else {
                LogManager.me().executeLoginLog(user, false, "密码错误")
                RU.failedMsg("密码错误！")
            }
        } else {
            LogManager.me().executeLoginLog(user, false, "账号不存在")
            RU.failedMsg("账号不存在！")
        }
    }

    override fun updateUserPermission(userId: String): List<String> {
        val per = ArrayList<String>().apply {
            //管理权限
            val user = sysUserMapper.selectById(userId)
            if (user.admin == 1) {
                if (user.superr == 1)
                    add("*")
                else
                    add("admin")
            }
        }
        authRedisService.setUserPermission(userId, per)
        return per
    }

    override fun updateUserRole(userId: String): List<String> {
        val role = ArrayList<String>()
        authRedisService.setUserRole(userId, role)
        return role
    }


}